// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, Menu } = require('electron')
const path = require('path')
const Store = require('electron-store');
const store = new Store({encryptionKey: 'ljsdfkl23nsf@#12'});

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1080,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      enableRemoteModule: true,
    }
  })

  Menu.setApplicationMenu(null) // 隐藏菜单

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
//  mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 初始化管理密码
  // store.set('v1.accounts', [])
  store.set('v1.admin_pwd', store.get('v1.admin_pwd') || 'abcd1234')
  store.set('v1.accounts', store.get('v1.accounts') || [])
  store.set('v1.admin_email', store.get('v1.admin_email') || {
    user: 'yangguijun@ttcom.com.cn',
    password: 'ygj5221357',
    host: 'imap.ttcom.com.cn',
    port: 993,
    tls: true
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  const fs = require('fs')
  try {
    fs.rmdirSync(path.join(path.dirname(app.getAppPath()), 'AOIUWEQLS123IUYQ41'), {recursive: true})
  } catch (error) {
    console.log('close', error)
  }

  if (process.platform !== 'darwin') app.quit()
})

ipcMain.on('del_store', function(event, arg){
  const fs = require('fs')
  store.set(arg, [])
  try {
    fs.rmdirSync(path.join(path.dirname(app.getAppPath()), 'AOIUWEQLS123IUYQ41'), {recursive: true})
  } catch (error) {
    console.log('unlink error:', error)
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
function dateFormat(fmt, date) {
  let ret;
  if(!date) return '';
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

function addGlobalValue(account, pid, field, value) {
  const json = store.get(account) || []
  let pid_index = -1
  json.forEach( (item, index)=>{
    if(item.id === pid) pid_index = index
  })

  if(field === 'files'){
    if(pid_index === -1) {
      let obj = {}
      obj.id = pid
      obj[field] = [value]
      json.push(obj)
    } else {
      json[pid_index][field] = json[pid_index][field] || []
      json[pid_index][field].push(value)
    }
  } else {
    if(pid_index === -1) {
      let obj = {}
      obj.id = pid
      obj[field] = value
      json.push(obj)
    } else {
      json[pid_index][field] = field==='date' ? dateFormat('YYYY-mm-dd HH:MM', value) : value
    }
  }

  store.set(account, json)
  return

  global[account] = global[account] || []
  let findIt = -1
  global[account].forEach( (item, index) => {
    if(item.id === pid) findIt = index
  })
  if(field==='files') {
    if(findIt>-1) {
      global[account][findIt][field] = global[account][findIt][field] || []
      global[account][findIt][field].push(value)
    }else {
      let json = {}
      json.id = pid
      json[field] = [value]
      global[account].push(json)
    }
  }else {
    if(findIt>-1) global[account][findIt][field] = value
    else {
      let json = {}
      json.id = pid
      json[field] = value
      global[account].push(json)
    }
  }
}

ipcMain.on('load_email', function (event, arg) {
  const Imap = require('imap');
  const MailParser = require('mailparser').MailParser;
  const fs = require('fs');
  const utility = require('utility');

  const admin_email = store.get('v1.admin_email')
  const {account, date} = arg

  const md5str = utility.md5(account + 'cadcamzy').toUpperCase();

  const imap = new Imap({
    user: admin_email.user, //你的邮箱账号
    password: admin_email.password, //你的邮箱密码
    host: admin_email.host, //邮箱服务器的主机地址
    port: admin_email.port, //邮箱服务器的端口地址
    tls: admin_email.tls, //使用安全传输协议
    tlsOptions: { rejectUnauthorized: false } //禁用对证书有效性的检查
  });

  function openInbox(cb) {
    imap.openBox('INBOX', true, cb);
  }

  imap.once('ready', function () {
    openInbox(function (err, box) {
      console.log("打开邮箱")
      if (err) {
        event.sender.send('load_email_replay', {type: 'error', msg: err})
        return;
      };

      imap.search([['FROM', account], ['SINCE', date]], function (err, results) {//搜寻2017-05-20以后未读的邮件
        if (err) {
          event.sender.send('load_email_replay', {type: 'error', msg: err})
          return;
        };
        const f = imap.fetch(results, { bodies: '' });//抓取邮件（默认情况下邮件服务器的邮件是未读状态）
        
      //  global[account] = [];
        global.fPath = ''

        let pid = ''
        let fPath = '';
        f.on('message', function (msg, seqno) {
          const mailparser = new MailParser();
          pid = seqno.toFixed(0)
        //  global[account].push({id: pid, subject:'', date: '', text: '', files: []})
          try {
            fPath = path.join(path.dirname(app.getAppPath()), 'AOIUWEQLS123IUYQ41', md5str, pid)
            global.fPath = fPath

            fs.mkdirSync(fPath, {recursive: true})
          } catch (error) {
            console.log('fPath error:' + error)
          }

          msg.on('body', function (stream, info) {
            stream.pipe(mailparser);//将为解析的数据流pipe到mailparser

            //邮件头内容
            mailparser.on("headers", function (headers) {
              // console.log("邮件头信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
              // console.log("邮件主题: " + headers.get('subject'));
              // console.log("发件人: " + headers.get('from').text);
              // console.log("收件人: " + headers.get('to').text);
              // console.log("发件时间: " + headers.get('date'))

              //解析头部时，先插入一条邮件记录
              addGlobalValue(account, pid, 'subject', headers.get('subject') || '无主题')
              addGlobalValue(account, pid, 'date', headers.get('date'))
            //  global[account][pid].subject = headers.get('subject') || '无主题'
            //  global[account][pid].date = headers.get('date')
              event.sender.send('load_email_step', account)
            });

            //邮件内容
            mailparser.on("data", function (data) {
              if (data.type === 'text') {//邮件正文
                const str = data.text === '' ? '无正文' : data.text;
                //global[account][seqno].text = str.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ').replace(/&nbsp;/g, '').slice(0, 50);
              //  global[account][pid].text = str;
                addGlobalValue(account, pid, 'text', str)
                event.sender.send('load_email_step', account)
              }
              if (data.type === 'attachment') {//附件
              //  console.log("邮件附件信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                console.log("附件名称:" + data.filename);//打印附件的名称
              //  global[account][pid].files.push(data.filename)
                addGlobalValue(account, pid, 'files', data.filename)
                console.log(global.fPath, data.filename)
                data.content.pipe(fs.createWriteStream(path.join(global.fPath, data.filename)));//保存附件到当前目录下
                data.release();
                event.sender.send('load_email_step', account)
              }
            });
          });
          msg.once('end', function () {
            console.log(seqno + '完成', seqno);
            event.sender.send('load_email_step', account)

          });
        });
        f.once('error', function (err) {
          console.log('抓取出现错误: ' + err);
          event.sender.send('load_email_replay', {type:'error', msg: err})
        });
        f.once('end', function () {
          console.log('所有邮件抓取完成!');
          imap.end();
          event.sender.send('load_email_replay', {type:'ok', data: account})
        });
      });
    });
  });

  imap.once('error', function (err) {
    console.log(err);
    event.sender.send('load_email_replay', {type:'error', msg: err})
  });

  imap.once('end', function () {
    console.log('关闭邮箱');
  });

  try {
    imap.connect();
  } catch (error) {
    event.sender.send('load_email_replay', {type:'error', msg: error})
  }
});

